<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { UPDATE_MODEL_EVENT } from '@jctech/constants/event';
import { textToValueArr, valueToTextArr } from '@jctech/components/common/helper';
import { checkboxEmits, chexkboxProps } from './checkboxSrc';

const props = defineProps(chexkboxProps);

const emits = defineEmits(checkboxEmits);

defineOptions({
  name: 'CCheckboxGroup'
});

const checkboxRef = ref(null);
const propsModelValue = computed(() => {
  return valueToTextArr(props.modelValue, props.source);
});

const handleUpdate = (value) => {
  if (!Array.isArray(value)) {
    return;
  }
  const valueArr = textToValueArr(value, props.source);
  if (props.isMutual || !Array.isArray(props.modelValue)) {
    emits(UPDATE_MODEL_EVENT, valueArr.length > 0 ? valueArr[valueArr.length - 1] : null);
  } else {
    emits(UPDATE_MODEL_EVENT, valueArr);
  }
};
</script>

<template>
  <el-form-item :label="props.label" :prop="props.prop" class="jctech-control-wrapper">
    <el-checkbox-group :model-value="propsModelValue" @update:model-value="handleUpdate">
      <el-checkbox v-for="item in props.source" :key="item.text" :label="item.text" />
    </el-checkbox-group>
  </el-form-item>
</template>

<style scoped lang="less"></style>
